package com.smsp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.smsp.dao.*;
import com.smsp.entity.Templet;
import com.smsp.entity.User;
import com.smsp.service.MessageDetailService;
import com.smsp.common.Const;
import com.smsp.common.ServerResponse;
import com.smsp.dao.impl.MessageWayImpl;
import com.smsp.entity.MessageDetail;
import com.smsp.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author DWJ
 */
@Service("MessageDetailService")
@Transactional
public class MessageDetailServiceImpl implements MessageDetailService {
    public Logger logger = LoggerFactory.getLogger(MessageDetailServiceImpl.class);

    @Autowired
    private MessageDetailMapper messsageDetailMapper;

    @Autowired
    private TempletMapper templetMapper;


    @Autowired
    private JedisClient jedisClient;

    @Override
    public ServerResponse createMessage(MessageDetail messageDetail) {

        if (messageDetail.getPhone() == null) {
            logger.debug("phone is null");
            return ServerResponse.createByErrorMessage("手机号未填写");
        }
        if (messageDetail == null || messageDetail.getTempletNo() == null) {
            logger.debug("messageDetail is null or messageDetail.templetNo is null");
            return ServerResponse.createByErrorMessage("参数错误");
        }

        String templeatString = jedisClient.get(Const.REDIS_PREFIX_TEMPLAET + messageDetail.getTempletNo());
        Templet templet = null;
        if (templeatString == null) {
            templet = templetMapper.selectByTemplateNo(messageDetail.getTempletNo());
            if (templet == null) {
                logger.debug("templet is not exist");
                return ServerResponse.createByErrorMessage("模板不存在");
            }

        } else {
            templet = JsonUtils.jsonToPojo(templeatString, Templet.class);
        }
        if (templet != null && !templet.getTempletStatus().equals("1")) {
            logger.debug("templet is not used", templet);
            return ServerResponse.createByErrorMessage("未审核模板不可用");
        }

        messageDetail.setCreateTime(new Date());
        messageDetail.setMessageContent("【" + templet.getTempletSign() + "】" + templet.getTempletContent());
//        MessageWay messageWay = new MessageWayImpl();
//        ServerResponse serverResponse = messageWay.sendMessage(messageDetail.getPhone(), templet.getTempletContent(), templet.getTempletSign(), templet.getTempletExtno());
//        if (!serverResponse.isSuccess()) {
//            /*未能请求服务*/
//            messageDetail.setMessageContent("1");
//        }
//        List<String> resList = java.util.Arrays.asList(serverResponse.getData().toString().split(","));
//        if (resList.get(1) != null && resList.get(1).trim().equals("0")) {
//            logger.debug("请求三方通道，数据解析出错");
//            /*短信下发成功*/
//            messageDetail.setMessageStatus("0");
//        } else {
//            logger.debug("三方通道服务器接收成功，数据不匹配");
//            /*异常状态*/
//            messageDetail.setMessageStatus("2");
//        }

        /*正在请求*/
        messageDetail.setMessageStatus(Const.MESSAGE_STATUS_REUESTING);
        messageDetail.setReceiveTime(new Date());
        if (messsageDetailMapper.insert(messageDetail) > 0) {
            updateMessageDetailStaust(messageDetail,templet);
            logger.info("明细创建成功！" + messageDetail.toString());
            return ServerResponse.cerateBySuccessMessage("明细创建成功！");
        }
        logger.debug("明细创建失败！" + messageDetail.toString());
        return ServerResponse.createByErrorMessage("明细创建失败");
    }

    @Override
    public ServerResponse deleteMessage(Integer id) {
        if (messsageDetailMapper.deleteByPrimaryKey(id) > 0) {
            logger.info("明细删除成功！" + id.toString());
            return ServerResponse.cerateBySuccessMessage("明细删除成功！");
        }
        logger.debug("明细删除失败！" + id.toString());
        return ServerResponse.createByErrorMessage("明细删除失败！");
    }

    @Override
    public ServerResponse selectAll() {
        List<MessageDetail> messageDetailList = messsageDetailMapper.selectAll();
        return ServerResponse.cerateBySuccess("所有明细查询成功！", messageDetailList);
    }

    @Override
    public ServerResponse selectListByUserId(User user) {
        if (user == null) {
            logger.debug("用户参数为空！");
            return ServerResponse.createByErrorMessage("用户参数为空！");
        }
        List<String> templateList = templetMapper.selectTemplateNosByUserId(user.getId());
        if (templateList == null || templateList.isEmpty()) {
            logger.debug("用户当前没有已审核模板！" + user.getUsername());
            return ServerResponse.createByErrorMessage("用户当前没有已审核模板！");
        }
        List<MessageDetail> messageDetailList = messsageDetailMapper.selectByTempletNo(templateList);
        logger.info("用户明细查询成功！");
        return ServerResponse.cerateBySuccess("明细查询成功！", messageDetailList);
    }


    @Override
    public PageInfo<MessageDetail> findMessageDetailByPage(int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        List<MessageDetail> list = messsageDetailMapper.selectAll();
        return new PageInfo<MessageDetail>(list);
    }

    private void updateMessageDetailStaust(MessageDetail messageDetail, Templet templet) {
//        new Thread() {
//            @Override
//            public void run() {
                MessageWay messageWay = new MessageWayImpl();
                ServerResponse serverResponse = messageWay.sendMessage(messageDetail.getPhone(), templet.getTempletContent(), templet.getTempletSign(), templet.getTempletExtno());
                if (!serverResponse.isSuccess()) {
                    /*未能请求服务*/
                    messageDetail.setMessageStatus(Const.MESSAGE_STATUS_REUEST_FAILED);
                }
                List<String> resList = java.util.Arrays.asList(serverResponse.getData().toString().split(","));
                if(resList==null){
                    logger.debug("请求三方通道失败");
                    /*短信下发成功*/
                    messageDetail.setMessageStatus(Const.MESSAGE_STATUS_REUEST_FAILED);
                }
                String resCode =resList.get(1).trim();
                if (resCode!=null && Integer.parseInt(resCode)!=0) {
                    logger.debug("请求三方通道成功，但数据解析出错");
                    /*短信下发成功*/
                    messageDetail.setMessageStatus(Const.MESSAGE_STATUS_ANALYSIS_FAILED);
                }
                logger.debug("msg id is:"+messageDetail.getId());
                messageDetail.setReceiveTime(new Date());
                messageDetail.setMessageStatus(Const.MESSAGE_STATUS_REUEST_SUCESS);
                if(messsageDetailMapper.updateByPrimaryKeySelective(messageDetail)==0){
                    logger.debug("状态修改失败");
                }
            }
//        }.start();
//    }
}
